<script setup>
import {ElMessage} from "element-plus";
import {getToken} from "@/utils/auth.js";
import {Plus} from "@element-plus/icons-vue";
import {toRefs} from "vue";

const uploadUrl = import.meta.env.VITE_BASE_URL + '/common/uploadFile';

const imgUrl = defineModel()
const props = defineProps({
    size: {
        type: Number,
        default: 60
    },
})

const { size } = toRefs(props)
function handleAvatarSuccess(res, file) {
    imgUrl.value = file.response.data
}

function beforeAvatarUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        ElMessage.error("上传头像图片大小不能超过 2MB!")
    }
    return isLt2M;
}
</script>

<template>
    <el-upload :action="uploadUrl"
               class="upload-a"
               :show-file-list="false"
               :headers="{'token':getToken()}"
               :on-success="handleAvatarSuccess"
               :before-upload="beforeAvatarUpload">
        <img v-if="imgUrl" :src="imgUrl" class="upload-a">
        <el-icon v-else class="upload-a">
            <Plus/>
        </el-icon>
    </el-upload>
</template>

<style scoped lang="scss">
$size: calc(v-bind(size)*1px);

.upload-a {
    display: flex;
    justify-content: center;
    align-items: center;
    width: $size;
    height: $size;
    line-height: $size;
    border: 1px dashed #d9d9d9;
}

</style>
